<template>
  <div class="app-container">
    <el-card class="teacher-info-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>教师信息</span>
      </div>
      <div class="teacher-info-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label class="info-label">教师ID：</label>
              <span class="info-value">{{ teacherId }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label class="info-label">教师姓名：</label>
              <span class="info-value">{{ teacherInfo.name }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label class="info-label">性别：</label>
              <span class="info-value">{{ teacherInfo.gender }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label class="info-label">是否在职：</label>
              <span class="info-value">
                <dict-tag :options="dict.type.effective" :value="teacherInfo.effective"/>
              </span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="bind-user-card">
      <div slot="header" class="clearfix">
        <span>用户绑定</span>
      </div>
      <div class="bind-user-content">
        <div v-if="bindingStatus === 'unbound'" class="bind-section">
          <!-- 已选用户信息区域 -->
          <div v-if="selectedUser" class="selected-user-info">
            <el-alert title="已选择用户" type="info" :closable="false">
              <div class="selected-user-details">
                <span>{{ selectedUser.userName }}</span>
                <span class="login-name">({{ selectedUser.nickName }})</span>
                <el-button type="text" size="small" class="unselect-btn" @click="unselectUser">取消选择</el-button>
              </div>
            </el-alert>
            <div class="action-buttons" style="margin-top: 15px; text-align: center;">
              <el-button type="primary" @click="handleBindUser" :loading="loading">确认绑定</el-button>
            </div>
          </div>

          <div class="search-section">
            <div class="search-header">
              <el-input
                v-model="searchUser"
                placeholder="搜索可用用户"
                clearable
                @keyup.enter.native="searchAvailableUsers"
                style="width: 300px;"
              >
                <el-button slot="append" icon="el-icon-search" @click="searchAvailableUsers"></el-button>
              </el-input>
              <el-button @click="$router.back()" style="margin-left: 10px;">返回</el-button>
            </div>

            <el-table v-loading="loading" :data="availableUsers" style="width: 100%" @row-click="selectUser">
              <el-table-column type="index" width="50" />
              <el-table-column prop="nickName" label="用户姓名" min-width="120" />
              <el-table-column prop="userName" label="登录账号" minwidth="150" />
              <el-table-column prop="dept" label="所属部门" minwidth="150" >
                <template slot-scope="{row}">
                  {{ row.dept.deptName || '无' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="selectUser(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="loadAvailableUsers"
              style="margin-top: 15px;"
            />
          </div>
        </div>

        <div v-else-if="bindingStatus === 'bound'" class="bound-section">
          <div class="bound-user-info">
            <div class="info-title">已绑定用户信息</div>
            <div class="info-details">
              <div class="info-row">
                <label>用户姓名：</label>
                <span>{{ boundUserInfo.nickName }}</span>
              </div>
              <div class="info-row">
                <label>登录账号：</label>
                <span>{{ boundUserInfo.userName }}</span>
              </div>
              <div class="info-row">
                <label>角色：</label>
                <span>{{ boundUserInfo.roleName }}</span>
              </div>
              <div class="info-row">
                <label>状态：</label>
                <span>
                  <dict-tag :options="dict.type.user_status" :value="boundUserInfo.status"/>
                </span>
              </div>
            </div>
          </div>

          <div class="action-buttons">
            <el-button type="danger" @click="handleUnbindUser" :loading="loading">解除绑定</el-button>
            <el-button @click="$router.back()">返回</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { unAssociatedUserList, associatedUserList, associate, unAssociate, getTeacherManage } from "@/api/ysg/teacherManage"

export default {
  name: "BindUser",
  dicts: ['user_status', 'effective'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 教师ID
      teacherId: parseInt(this.$route.params && this.$route.params.teacherId),
      // 教师信息
      teacherInfo: {},
      userInfo: {},
      // 绑定状态：unbound(未绑定), bound(已绑定)
      bindingStatus: 'unbound',
      // 已绑定的用户信息
      boundUserInfo: {},
      // 已选择的用户信息
      selectedUser: null,
      // 可用用户列表
      availableUsers: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
      },
      // 搜索关键词
      searchUser: '',
      // 绑定表单
      bindForm: {
        userId: '',
      }
    }
  },
  created() {
    if(this.teacherId) {
      this.loadTeacherInfo()
      this.checkBindingStatus()
    } else {
      this.$modal.notifyError("参数有误");
    }
  },
  methods: {
    /** 加载教师信息 */
    loadTeacherInfo() {
      getTeacherManage(this.teacherId).then(response => {
        this.teacherInfo = response.data
      })
    },

    /** 检查绑定状态 */
    checkBindingStatus() {
      this.loading = true
      // 查询已绑定的用户
      const query = {
        teacherId: this.teacherId,
        pageNum: 1,
        pageSize: 1
      }

      associatedUserList(query).then(response => {
        if (response.rows && response.rows.length > 0) {
          this.bindingStatus = 'bound'
          this.boundUserInfo = response.rows[0]
          console.log(this.boundUserInfo.status)
        } else {
          this.bindingStatus = 'unbound'
          this.loadAvailableUsers()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 加载可用用户列表 */
    loadAvailableUsers() {
      this.loading = true
      this.queryParams.teacherId = this.teacherId
      unAssociatedUserList(this.queryParams).then(response => {
        this.availableUsers = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 搜索可用用户 */
    searchAvailableUsers() {
      this.queryParams.pageNum = 1
      this.queryParams.nickName = this.searchUser
      this.loadAvailableUsers()
    },

    /** 选择用户 */
      selectUser(row) {
        this.selectedUser = row
        console.log(this.selectedUser)
        this.bindForm.userId = row.id
      },

      /** 取消选择用户 */
      unselectUser() {
        this.selectedUser = null
        this.bindForm.userId = ''
      },

      /** 绑定用户 */
      handleBindUser() {
        if (!this.selectedUser) {
          this.$modal.msgWarning("请选择要绑定的用户")
          return
        }

        this.loading = true
        const param = {
          teacherId: this.teacherId,
          userId: this.selectedUser.userId
        }

        associate(param).then(res => {
          this.$modal.msgSuccess("绑定成功")
          this.checkBindingStatus()
        }).catch(() => {
          this.loading = false
        })
      },

    /** 解除绑定 */
    handleUnbindUser() {
      this.$modal.confirm('确定要解除当前绑定吗？').then(() => {
        this.loading = true
        const param = {
          teacherId: this.teacherId,
          userId: this.boundUserInfo.userId
        }

        unAssociate(param).then(res => {
          this.$modal.msgSuccess("解除绑定成功")
          this.checkBindingStatus()
        }).catch(() => {
          this.loading = false
        })
      })
    }
  }
}
</script>
<style scoped>
.teacher-info-card {
  background-color: #f5f7fa;
}

.teacher-info-content {
  padding: 10px 0;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
  min-width: 60px;
}

.info-value {
  color: #303133;
}

.bind-user-card {
  min-height: 400px;
}

.bind-user-content {
  padding: 20px 0;
}

.bind-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.bind-form {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-section {
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 15px;
    }

    .search-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
    }

    .selected-user-info {
      margin-bottom: 15px;
    }

    .selected-user-details {
      display: flex;
      align-items: center;
    }

    .login-name {
      color: #606266;
      margin-left: 5px;
    }

    .unselect-btn {
      margin-left: 15px;
      color: #f56c6c;
    }

.bound-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  gap: 30px;
}

.bound-user-info {
  width: 100%;
  max-width: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.info-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

.info-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-row label {
  font-weight: bold;
  color: #606266;
  min-width: 80px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

@media (max-width: 768px) {
  .teacher-info-content .el-row .el-col {
    width: 100%;
    margin-bottom: 10px;
  }
}
::v-deep .el-empty {
  padding:0 0 20px 0;
}
</style>
